package com.budwk.app.sqfw.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.component.FromSummaryComponent;
import com.budwk.app.sqfw.component.MeetingMinutesComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.dto.SqfwFormSummaryWithFlowDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.vo.AreaAddressVo;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sqfw.vo.SysDictResVo;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadPoolExecutor;

@IocBean(name = "meetingMinutesService")
@Slf4j
public class MeetingMinutesServiceImpl implements MeetingMinutesService, SecurityInvestigationService {

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private MeetingMinutesComponent meetingMinutesComponent;
    @Inject
    private CommunityStreetComponent communityStreetComponent;
    @Inject
    private FromSummaryComponent fromSummaryComponent;
    @Inject
    private SqfwDownRecordlogService sqfwDownRecordlogService;

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    @Override
    public Result<?> addMeetingMinutes(SqfwFormSummaryWithFlowDTO reqVo) {
        // 1 校验基本参数
        meetingMinutesComponent.checkAddMeetParam(reqVo);
        // 2 入库
        SqfwFormSummaryWithFlowDTO reqDto = fromSummaryComponent.addFromSummary(reqVo);
        // 3 生成pdf
        meetingMinutesComponent.generatePDF(reqDto.getCompleteFlow(), reqDto.getFormSummary());
        return Result.success();
    }

    @Override
    public Result<?> afreshGeneratePDF(String completeflowId) {
        Sqfw_completeflow completeflow = sqfwCompleteflowService.fetch(completeflowId);
        if (completeflow == null) {
            throw new AppException("任务流数据不存在");
        }
        Sqfw_formSummary formSummary = sqfwFormSummaryService.fetch(Cnd.where(Sqfw_formSummary::getSqfwFlowId, "=", completeflow.getId()));
        if (formSummary == null) {
            throw new AppException("数据不存在");
        }
        meetingMinutesComponent.generatePDF(completeflow, formSummary);
        return Result.success();
    }

    @Override
    public Result<?> queryMeetNameHistory(String a20) {
        if (StringUtils.isEmpty(a20)) {
            throw new AppException("请输入内容！");
        }
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        Sqfw_formSummaryForAdminVO bean = new Sqfw_formSummaryForAdminVO();
        // 数据权限操作查询条件
        AreaAddressVo areaAddressVo = AuthorityUtil.checkFormSummaryAreaPermission(bean);
        AuthorityUtil.commonPermissionLikeQuery(criSql, areaAddressVo);
        criSql.andLike(Sqfw_formSummary::getA20, a20);
        criSql.andEquals(Sqfw_formSummary::getType, SupportBusinessTypeEnum.MEET_RECORD.getName());
        List<Sqfw_formSummary> list = sqfwFormSummaryService.query(cri);
        return Result.data(list);
    }

    @Override
    public Result<?> downloadFile(String sqfwId, String excelType, String code) {
        // 1 下载台账
        if (DictConstants.MEET_RECORD_TYPES_EXCEL.equals(code)) {
            // 判断是否已经下载
            return Result.data(meetingMinutesComponent.generateMeetExcelLedger(sqfwId));
        }
        if (DictConstants.MEET_RECORD_TYPES_PDF.equals(code)) {
            return Result.data(meetingMinutesComponent.generatePDFMeetingRecordCollection(sqfwId));
        }
        return null;
    }

    @Override
    public boolean checkCurrentUserAuthority() {
        return false;
    }

    @Override
    public Result<Pagination> listSummaryByPage(Sqfw_formSummaryForAdminVO forAdminVo) {
        Criteria criteria = meetingMinutesComponent.buildQueryCond(forAdminVo);
        // 2 分页查询
        Pagination pagination = sqfwFormSummaryService.listPage(forAdminVo.getPageNo(), forAdminVo.getPageSize(), criteria);
        if (pagination.getTotalCount() == 0) {
            return Result.data(pagination);
        }
        // 空值处理
        pagination.setList(CommonComponent.formatSqfwFormSummarysNull(pagination.getList(Sqfw_formSummary.class)));
        return Result.data(pagination);
    }

    @Override
    public String generateServiceRecordPdfCollZipForBM(Sqfw_formSummaryForAdminVO bean) {
        // 1 构建查询条件
        Criteria cnd = meetingMinutesComponent.buildQueryCond(bean);
        // 按照条件导出PDF
        String url = communityStreetComponent.generateServiceRecordPdfCollZipForBM(cnd);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(bean), JSONObject.toJSONString(Result.data(url)), "按照查询条件导出会议记录PDF文件", url, null);
        return url;
    }

    @Override
    public String generateServiceRecordExcelCollZipForBM(Sqfw_formSummaryForAdminVO bean) {
        Criteria cri = meetingMinutesComponent.buildQueryCond(bean);
        // 2 生成台账内容
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.query(cri);
        // 3 生成台账
        String url = meetingMinutesComponent.generateExcelFile(formSummaryList,null);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(bean), JSONObject.toJSONString(Result.data(url)), "按照查询条件导出会议记录Excel文件", url, null);
        return url;
    }

    @Override
    public Criteria buildQueryCond(Sqfw_formSummaryForAdminVO forAdminVo) {
        return null;
    }


    @Override
    public String mergeExcelLedgerBySqfwIds(List<String> sqfwIdList, String fileNameSuffix) {
        // 1 查询数据
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andIn(Sqfw_formSummary::getSqfwId, sqfwIdList.toArray(new String[0])).andEquals(Sqfw_formSummary::getType, SupportBusinessTypeEnum.MEET_RECORD.getName());
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.query(cri);
        if (formSummaryList == null || formSummaryList.size() == 0) {
            return null;
        }
        // 2 生成台账内容
        String url = meetingMinutesComponent.generateExcelFile(formSummaryList,null);

        String meetExcel = CommonComponent.getMeetRecordTypes().get(DictConstants.MEET_RECORD_TYPES_EXCEL);
        CommonComponent.insertDownRecordLog(JSONObject.toJSONString(sqfwIdList), JSONObject.toJSONString(Result.data(url)),
                String.format("%s%s","批量下载", meetExcel), url, null);
        return url;
    }

    @Override
    public String mergeExcelLedgerByIds(List<String> ids) {
        // 1 查询数据
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andIn(Sqfw_formSummary::getId, ids.toArray(new String[0])).andEquals(Sqfw_formSummary::getType, SupportBusinessTypeEnum.MEET_RECORD.getName());
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.query(cri);
        if (formSummaryList == null || formSummaryList.size() == 0) {
            return null;
        }
        // 2 是否已经下载过 如果已经下载过 直接下载
        String meetExcel = CommonComponent.getMeetRecordTypes().get(DictConstants.MEET_RECORD_TYPES_EXCEL);
        String meetExcelName = String.format("%s%s","下载", meetExcel);
        String idsStr = JSONObject.toJSONString(ids);
        Optional<String> optional = sqfwDownRecordlogService.getUrlByEntityIdAndTitle(idsStr, meetExcelName);
        if (optional.isPresent()) {
            log.info("mergeExcelLedgerByIds getUrlByEntityIdAndTitle res: {}", optional.get());
            return optional.get();
        }
        // 3 重新生成台账内容
        String url = meetingMinutesComponent.generateExcelFile(formSummaryList, null);
        // 4 记录日志信息
        CommonComponent.insertDownRecordLog(idsStr, JSONObject.toJSONString(Result.data(url)), meetExcelName, url, idsStr);
        log.info("mergeExcelLedgerByIds url: {}", url);
        return url;
    }

    @Override
    public Result<?> listDownFileTypes(String sqfwId) {
        List<SysDictResVo> list = meetingMinutesComponent.listDownFileTypes(sqfwId);
        return Result.data(list);
    }
}

